<template>
  <view class="wheel-canvas-wrapper">
    <canvas 
      :canvas-id="canvasId"
      :id="canvasId" 
      type="2d"
      class="wheel-canvas"
      @touchstart="onTouchStart"
      @touchend="onTouchEnd"
    ></canvas>
    
    <!-- GO 按钮 -->
    <view class="go-button" @click="startSpin">
      <text class="go-text">GO</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  /**
   * 转盘选项配置
   */
  options: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['spin-end'])

const canvasId = ref('wheel-canvas-' + Date.now())
const canvasContext = ref(null)
const isSpinning = ref(false)
const currentRotation = ref(0)
const canvasSize = ref(300)

/**
 * 初始化 Canvas
 */
const initCanvas = async () => {
  try {
    console.log('开始初始化原生 Canvas...')
    
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    const rpxToPx = systemInfo.windowWidth / 750
    const size = Math.floor(600 * rpxToPx)
    canvasSize.value = size
    
    // 获取 Canvas 上下文
    const query = uni.createSelectorQuery()
    query.select(`#${canvasId.value}`)
      .fields({ node: true, size: true })
      .exec((res) => {
        if (res && res[0]) {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          
          const dpr = systemInfo.pixelRatio || 2
          canvas.width = size * dpr
          canvas.height = size * dpr
          ctx.scale(dpr, dpr)
          
          canvasContext.value = ctx
          
          console.log('✅ Canvas 初始化成功，尺寸:', size)
          
          // 绘制转盘
          drawWheel()
          
          uni.showToast({
            title: '转盘加载成功',
            icon: 'success',
            duration: 1500
          })
        } else {
          console.error('Canvas 节点获取失败')
        }
      })
  } catch (error) {
    console.error('初始化失败:', error)
    uni.showToast({
      title: '转盘加载失败',
      icon: 'none'
    })
  }
}

/**
 * 绘制转盘
 */
const drawWheel = () => {
  if (!canvasContext.value || props.options.length === 0) return
  
  const ctx = canvasContext.value
  const size = canvasSize.value
  const centerX = size / 2
  const centerY = size / 2
  const radius = size * 0.4
  
  console.log('绘制转盘，半径:', radius)
  
  // 清空画布
  ctx.clearRect(0, 0, size, size)
  
  // 保存当前状态
  ctx.save()
  
  // 移动到中心点并旋转
  ctx.translate(centerX, centerY)
  ctx.rotate((currentRotation.value * Math.PI) / 180)
  ctx.translate(-centerX, -centerY)
  
  const anglePerOption = (2 * Math.PI) / props.options.length
  
  // 绘制扇形
  props.options.forEach((option, index) => {
    const startAngle = index * anglePerOption - Math.PI / 2
    const endAngle = startAngle + anglePerOption
    
    // 绘制扇形
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.arc(centerX, centerY, radius, startAngle, endAngle)
    ctx.closePath()
    
    // 填充颜色
    ctx.fillStyle = option.color
    ctx.fill()
    
    // 描边
    ctx.strokeStyle = '#FFFFFF'
    ctx.lineWidth = 3
    ctx.stroke()
    
    // 绘制文字
    ctx.save()
    const textAngle = startAngle + anglePerOption / 2
    const textX = centerX + Math.cos(textAngle) * (radius * 0.7)
    const textY = centerY + Math.sin(textAngle) * (radius * 0.7)
    
    ctx.translate(textX, textY)
    ctx.rotate(textAngle + Math.PI / 2)
    
    ctx.fillStyle = '#FFFFFF'
    ctx.font = `bold ${size * 0.05}px sans-serif`
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(option.text, 0, 0)
    
    ctx.restore()
  })
  
  // 绘制中心圆
  ctx.beginPath()
  ctx.arc(centerX, centerY, radius * 0.15, 0, 2 * Math.PI)
  ctx.fillStyle = '#FFFFFF'
  ctx.fill()
  ctx.strokeStyle = '#E0E0E0'
  ctx.lineWidth = 2
  ctx.stroke()
  
  // 恢复状态
  ctx.restore()
  
  console.log('转盘绘制完成，扇形数量:', props.options.length)
}

/**
 * 开始转动
 */
const startSpin = () => {
  if (isSpinning.value || props.options.length === 0) return
  
  isSpinning.value = true
  
  // 随机选择结果
  const randomIndex = Math.floor(Math.random() * props.options.length)
  const anglePerOption = 360 / props.options.length
  
  // 计算目标角度
  const spins = 5
  const targetAngle = 360 * spins + randomIndex * anglePerOption + Math.random() * anglePerOption
  
  // 执行动画
  animateWheel(targetAngle, randomIndex)
}

/**
 * 转盘动画
 * @param {number} targetAngle - 目标角度
 * @param {number} resultIndex - 结果索引
 */
const animateWheel = (targetAngle, resultIndex) => {
  const duration = 3000
  const startTime = Date.now()
  const startRotation = currentRotation.value
  
  const animate = () => {
    const elapsed = Date.now() - startTime
    const progress = Math.min(elapsed / duration, 1)
    
    // 缓动函数：先快后慢
    const easeOut = 1 - Math.pow(1 - progress, 3)
    
    currentRotation.value = startRotation + targetAngle * easeOut
    
    // 重新绘制
    drawWheel()
    
    if (progress < 1) {
      requestAnimationFrame(animate)
    } else {
      // 动画结束
      isSpinning.value = false
      emit('spin-end', props.options[resultIndex])
    }
  }
  
  animate()
}

/**
 * 触摸事件处理
 */
const onTouchStart = () => {
  // 可以添加触摸交互
}

const onTouchEnd = () => {
  // 可以添加触摸交互
}

onMounted(() => {
  setTimeout(() => {
    initCanvas()
  }, 500)
})

/**
 * 暴露方法给父组件
 */
defineExpose({
  startSpin
})
</script>

<style lang="scss" scoped>
.wheel-canvas-wrapper {
  position: relative;
  width: 600rpx;
  height: 600rpx;
  
  .wheel-canvas {
    width: 100%;
    height: 100%;
  }
  
  .go-button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #FF6B9D 0%, #C06595 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 20rpx rgba(255, 107, 157, 0.4);
    cursor: pointer;
    
    &:active {
      transform: translate(-50%, -50%) scale(0.95);
    }
    
    .go-text {
      color: white;
      font-size: 40rpx;
      font-weight: bold;
    }
  }
}
</style>

